﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using CommonBase;
using MCDomain.DataAccess;
using MCDomain.Model;
using MContracts.Controls.Dialogs;
using MContracts.ViewModel;
using MContracts.Controls;
using MContracts.ViewModel.Helpers;

using WindowsTaskDialog;
using McUIBase.ViewModel;
using McUIBase.Factories;

namespace MContracts
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        readonly MainWindowViewModel _viewModel = null;

        public MainWindow()
        {
            
            InitializeComponent();

            _viewModel = new MainWindowViewModel();
            EventHandler handler = null;
            handler = delegate
            {
                _viewModel.Closable.RequestClose -= handler;
                this.Close();
            };
            _viewModel.Closable.RequestClose += handler;
            this.DataContext = _viewModel;
            
            _viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(viewModel_PropertyChanged);
            _viewModel.QueryCloseWorkspace += new EventHandler<System.ComponentModel.CancelEventArgs>(viewModel_QueryCloseWorkspace);

            Loaded += new RoutedEventHandler(MainWindow_Loaded);
            _viewModel.RequestEditRelation += new EventHandler<ContractArgs>(viewModel_RequestEditRelation);
            _viewModel.ContractCreateRefused += new EventHandler<ContractArgs>(viewModel_ContractCreateRefused);
            _viewModel.RequestSaveModifiedWorkspace += viewModel_RequestSaveModifiedWorkspace;

            ContextFactoryService.Instance.Connect();
            

        }

        void viewModel_RequestSaveModifiedWorkspace(object sender, EventParameterArgs<bool> e)
        {
            e.Parameter =
                MessageBox.Show("Перед продолжением необходимо сохранить изменения. Сохранить и продолжить?",
                                "Выполнение операции", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                MessageBoxResult.Yes;

        }

        void viewModel_ContractCreateRefused(object sender, ContractArgs e)
        {
            MessageBox.Show("Нельзя добавить договор с соисполнителями для договора с соисполнителями.",
                            "Создание договора", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        void viewModel_RequestEditRelation(object sender, ContractArgs e)
        {
            using (
                var contractRelationsEditorViewModel =
                    new ContractRelationsEditorViewModel(RepositoryFactory.CreateContractRepository())
                        {WrappedDomainObject = _viewModel.SelectedContract, MainViewModel = _viewModel})
            {
                var editor = new ContractRelationsEditor()
                                 {
                                     DataContext = contractRelationsEditorViewModel
                                 };

                editor.ShowDialog();
            }
        }

        void viewModel_QueryCloseWorkspace(object sender, System.ComponentModel.CancelEventArgs e)
        {            
            var ws = (sender as WorkspaceViewModel);
            if (ws.IsModified)
            {
                ws.IsActive = true;

                var typeViewModel = String.Empty;
                if (ws is ContractViewModel)
                    typeViewModel = "Документ";
                if (ws is CatalogViewModel)
                    typeViewModel = "Справочник";

                var mbRes =
                    MessageBox.Show(
                        string.Format("{1} {0} был изменён. Сохранить изменения перед закрытием?", ws.DisplayName, typeViewModel),
                        "Учёт договоров", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                switch (mbRes)
                {
                    case MessageBoxResult.Yes:
                        if (!ws.SaveCommand.CanExecute(null))
                        {
                            MessageBox.Show(string.Format("{0} не может быть сохранён прямо сейчас, так как содержит ошибки, которые должны быть исправлены. Перейдите на документ и посмотрите сообщения об ошибках.", typeViewModel),
                                "Учёт договоров", MessageBoxButton.OK, MessageBoxImage.Information);
                            e.Cancel = true;                        

                        }
                        else
                        {
                            _viewModel.SaveWorkspace(ws);
                            
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                   default:
                        break;
                }
            }

            if (ws is ContractViewModel)
            {
                _viewModel.ShowContractRepositoryCommand.Execute(null);
            }
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {                           
            //HideGroupsRibbonItems();
            _viewModel.ShowContractRepositoryCommand.Execute(this);
            _viewModel.ShowActRepositoryCommand.Execute(this);
            _viewModel.ShowContractRepositoryCommand.Execute(this);
            _viewModel.ShowContractRepository();
            _viewModel.RequestDeleteContract += viewModel_RequestDeleteContract;

            var workspace = _viewModel.Workspaces.FirstOrDefault(vm => vm is ContractRepositoryViewBasedViewModel) as ContractRepositoryViewBasedViewModel;
            if (workspace != null)
            {
                var vm = new FilterContractsViewModel(workspace.Repository);
                filterContracts1.DataContext = vm;
                vm.MainViewModel = _viewModel;
                vm.ApplySelectedFilter();

            }
        }

        private void viewModel_RequestDeleteContract(object sender, DeleteContractArgs e)
        {
            
            //const int DELETE = 1;
            //const int CANCEL = 2;

            var dlg = new TaskDialog();
            dlg.Content = string.Format("Продолжение выполнения приведёт к удалению  договора №{0} и связанных с ним данных. Продолжить?", e.ContractState.Internalnum);
            //dlg.Buttons = new TaskDialogButton[] { new TaskDialogButton() { ButtonId = DELETE, ButtonText = "Удалить" }, new TaskDialogButton(CANCEL, "Не удалять") };
            dlg.MainIcon = TaskDialogIcon.Information;
            //dlg.MainInstruction = "";
            dlg.WindowTitle = "Удаление договора";
            //dlg.EnableHyperlinks = true;
            //dlg.Footer = string.Format("<A HREF=\"file:///{0}\"> Показать журнал </A>", GetLogFileName());
            //dlg.Callback += new TaskDialogCallbackEventHandler(dlg_Callback);
            dlg.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
            e.Cancel = (TaskDialogCommonButtons)dlg.Show(IntPtr.Zero) == TaskDialogCommonButtons.No;
         
        }


        #region MenuBuilding

        void viewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //устанавливаем меню в зависимости от воркспейса
            //if (e.PropertyName == "ActiveWorkspace")
            //{
            //    SetRequiredMenu(_viewModel.ActiveWorkspace);
            //}
        }

        //private void SetRequiredMenu(WorkspaceViewModel wvm)
        //{
        //    HideGroupsRibbonItems();
            
        //    ContractsGroup.Visibility = Visibility.Visible;
        //    ContractTabItem.Visibility = Visibility.Visible;
        //    SelectedContractTabItem.Visibility = Visibility.Visible;


            
        //    SetVisibilityGroups(ContractTabItem, Visibility.Visible);
        //    SetVisibilityGroups(SelectedContractTabItem, Visibility.Visible);
           

        //    if (wvm is ContractRepositoryViewBasedViewModel)
        //    {
        //        ContractRepositoryMenuBuild();
        //    }
        //    if (wvm is ActRepositoryViewModel)
        //    {
        //        ActRepositoryMenuBuild();
        //    }
        //    if (wvm is ContractViewModel)
        //    {
        //        ContractMenuBuild();
        //    }
        //    if (wvm is CatalogViewModel)
        //    {
        //        CatalogMenuBuild();
        //    }
        //    if (wvm is DisposalsRepositoryViewModel)
        //    {
                
        //    }
        //}

        //private void ActRepositoryMenuBuild()
        //{
        //    ActTabItem.Visibility = Visibility.Visible;
        //    ActTabItem.IsSelected = true;
        //    if (firstload)
        //    {
        //        BeginDatePicker.SelectedDate = new DateTime(DateTime.Now.Year, 1, 1);
        //        EndDatePicker.SelectedDate = new DateTime(DateTime.Now.Year, 12, 31);
        //        firstload = false;
        //    }
        //    else
        //    {
        //        BeginDatePicker.SelectedDate = (_viewModel.ActiveWorkspace as ActRepositoryViewModel).BeginDate;
        //        EndDatePicker.SelectedDate = (_viewModel.ActiveWorkspace as ActRepositoryViewModel).EndDate;
        //        ContractsListBox.ItemsSource = (_viewModel.ActiveWorkspace as ActRepositoryViewModel).SelectedContracts;
        //    }
        //}

 

        //private void CatalogMenuBuild()
        //{
        //    CatalogTabItem.IsSelected = true;
        //}

        //private void ContractMenuBuild()
        //{
        //    SelectedContractTabItem.IsSelected = true;
        //}

        /// <summary>
        /// строит риббон для реестра договоров
        /// </summary>
        private void ContractRepositoryMenuBuild()
        {
            ContractTabItem.IsSelected = true;
        }

        //public void HideGroupsRibbonItems()
        //{
        //    foreach (RibbonTabItem RI in MainRibbon.Tabs.Where(x => x.Group != null))
        //    {
        //        RI.Visibility = System.Windows.Visibility.Collapsed;
        //        SetVisibilityGroups(RI, Visibility.Collapsed);
        //    }
        //}

        //private void SetVisibilityGroups(RibbonTabItem RTI, Visibility Vis)
        //{
        //    foreach (FrameworkElement FE in RTI.Groups)
        //    {
        //        FE.Visibility = Vis;
        //    }
        //}

        #endregion

        private void FilterContracts_DescriptionsChanged(object sender, EventArgs e)
        {
            //if (viewModel.ActiveWorkspace is ContractRepositoryViewModel)
            //{
            //    (viewModel.ActiveWorkspace as ContractRepositoryViewModel).Filters = (sender as FilterContracts).Filters.ToList();
            //}
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
            //var dlg = new Controls.Dialogs.ReportViewerHost();
            //dlg.ShowDialog();
        }

        private void BeginDatePicker_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //if (_viewModel.ActiveWorkspace is ActRepositoryViewModel)
            //{
            //    if (BeginDatePicker.SelectedDate.HasValue && EndDatePicker.SelectedDate.HasValue)
            //        (_viewModel.ActiveWorkspace as ActRepositoryViewModel).FilteringActsByDates(BeginDatePicker.SelectedDate.Value, EndDatePicker.SelectedDate.Value);
            //}
            }

        private void EndDatePicker_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //if (_viewModel.ActiveWorkspace is ActRepositoryViewModel)
            //{
            //    if (BeginDatePicker.SelectedDate.HasValue && EndDatePicker.SelectedDate.HasValue)
            //        (_viewModel.ActiveWorkspace as ActRepositoryViewModel).FilteringActsByDates(BeginDatePicker.SelectedDate.Value, EndDatePicker.SelectedDate.Value);
            //}
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
          /*  if (viewModel.ActiveWorkspace is ActRepositoryViewModel)
            {
                FilterActsDialog dlg = new FilterActsDialog()
                                           {
                                               Contracts = RepositoryFactory.CreateContractRepository().Contracts.Where(x=>!x.IsDeleted).ToList(),
                                               SelectedContracts = (viewModel.ActiveWorkspace as ActRepositoryViewModel).SelectedContracts
                                           };

                if (dlg.ShowDialog() == true)
                {
                    (viewModel.ActiveWorkspace as ActRepositoryViewModel).FilteringActsByContracts(dlg.SelectedContracts);
                    ContractsListBox.ItemsSource = null;
                    ContractsListBox.ItemsSource = dlg.SelectedContracts;
                }
            } */
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (_viewModel.ActiveWorkspace is ActRepositoryViewModel)
            {
                //сбрасываем фильтр по договорам
                var temp = new List<Contractdoc>();

                (_viewModel.ActiveWorkspace as ActRepositoryViewModel).SelectedContracts = temp;
                //ContractsListBox.ItemsSource = temp;
                (_viewModel.ActiveWorkspace as ActRepositoryViewModel).FilteringActsByContracts(temp);
            }
            
        }





        public WorkspaceViewModel ContractRepositoryWorkspace { get; private set; }


    }
}
